<template>
  <div v-loading="loading">
    <el-form
      ref="formRef"
      :rules="rules"
      :model="detail"
      label-width="80px"
      style="max-width: 500px"
    >
      <el-form-item prop="UserCode" label="账号">
        <el-input v-model="detail.UserCode" clearable />
      </el-form-item>
      <el-form-item prop="UserName" label="姓名">
        <el-input v-model="detail.UserName" clearable />
      </el-form-item>
      <el-form-item prop="IsAdmin" label="管理员">
        <el-switch active-value="Y" inactive-value="N" v-model="detail.IsAdmin" />
      </el-form-item>
    </el-form>
    <div v-loading="loading" class="my_opt_btn_pannel">
      <div style="text-align: left">
        <el-button @click="router.back()">返回</el-button>
      </div>
      <div style="text-align: right; padding-right: 20px">
        <el-button v-if="optUser.isAdm" type="primary" @click="submit">保存</el-button>
        <el-button
          :disabled="!detail.Pk || (detail.Pk !== optUser.userId && !optUser.isAdm)"
          @click="showPwdChange = true"
          >修改密码</el-button
        >
        <el-button v-if="optUser.isAdm" @click="setInfo()">重置</el-button>
      </div>
    </div>
    <el-dialog v-model="showPwdChange" title="提示" width="600px">
      <ChangePwd
        :userid="detail.Pk!"
        @cancel="showPwdChange = false"
        @success="showPwdChange = false"
      />
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { getUser, saveUser } from '@/api/user'
import { useUserStore } from '@/stores/user'
import type { UserModel } from '@/type/User'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import ChangePwd from '@/components/ChangePwd.vue'
const showPwdChange = ref(false)
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const detail = ref<UserModel>({ IsAdmin: 'N' })
const optUser = useUserStore()
let detail_copy = ''
onMounted(async () => {
  if (route.query.pk) {
    loading.value = true
    try {
      detail.value = (await getUser(route.query.pk.toString())).Data[0]!
    } finally {
      loading.value = false
    }
  }
  detail_copy = JSON.stringify(detail.value)
})
const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  UserCode: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  UserName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
})
const setInfo = () => {
  detail.value = JSON.parse(detail_copy)
}
const submit = async () => {
  loading.value = true
  try {
    await formRef.value?.validate()
    const r = await saveUser(detail.value)
    detail_copy = JSON.stringify(r.Data[0]!)
    detail.value = r.Data[0]!
    ElMessage.success('操作成功')
  } finally {
    loading.value = false
  }
}
</script>
